package com.sunlee.common.core.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.sunlee.common.core.entity.PageData;
import com.sunlee.common.core.utils.ConvertUtils;
import com.sunlee.common.core.service.BaseCrudService;
import org.springframework.beans.BeanUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * CRUD基础服务类
 *
 * @author sunlee
 */
public abstract class BaseBaseCrudServiceImpl<M extends BaseMapper<T>, T, D> extends BaseServiceImpl<M, T> implements BaseCrudService<T, D> {

    protected Class<D> currentDtoClass() {
        return (Class<D>) ReflectionKit.getSuperClassGenericType(getClass(), BaseBaseCrudServiceImpl.class, 2);
    }

    @Override
    public PageData<D> pageOwn(Map<String, Object> params) {
        IPage<T> page = baseDao.selectPage(
                getPage(params, null, false),
                getWrapper(params)
        );

        return getPageData(page, currentDtoClass());
    }

    @Override
    public List<D> listOwn(Map<String, Object> params) {
        List<T> entityList = baseDao.selectList(getWrapper(params));

        return ConvertUtils.sourceToTarget(entityList, currentDtoClass());
    }

    /**
     * 获取基本查询wrapper
     *
     * @param params map
     * @return LambdaQueryWrapper
     */
    public abstract LambdaQueryWrapper<T> getWrapper(Map<String, Object> params);

    @Override
    public D getOwn(Long id) {
        T entity = baseDao.selectById(id);

        return ConvertUtils.sourceToTarget(entity, currentDtoClass());
    }

    @Override
    public void saveOwn(D dto) {
        T entity = ConvertUtils.sourceToTarget(dto, currentModelClassOwn());
        insertOwn(entity);

        //copy主键值到dto
        BeanUtils.copyProperties(entity, dto);
    }

    @Override
    public void updateOwn(D dto) {
        T entity = ConvertUtils.sourceToTarget(dto, currentModelClassOwn());
        updateByIdOwn(entity);
    }

    @Override
    public void deleteOwn(Long[] ids) {
        baseDao.deleteBatchIds(Arrays.asList(ids));
    }
}